<template>
  <div class="page page-home" v-loading="loading">
    <div class="images">
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <date-time
              :dateTime="form.dateTime"
              @change-date-time="changeDateTime"
              style="margin-bottom: 30px"
            >
            </date-time>
          </el-col>
          <el-col :span="16">
            <el-form
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
            >
              <el-form-item label="产品型号">
                <el-select
                  size="mini"
                  style="width: 100%"
                  @change="changeProductLine"
                  v-model="form.k1002"
                  placeholder="请选择产品型号"
                >
                  <el-option
                    v-for="(item, index) in productionLineList"
                    :key="index"
                    :value="item"
                    :label="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="序列号">
                <el-input
                  v-model="serialNumber"
                  placeholder="请输入序列号"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="queryStationBynumber"
                  >查询</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>

      <el-row :gutter="20">
        <el-col :span="8">
          <div class="resume-checkbox">
            <el-table
              max-height="650px"
              size="mini"
              ref="table"
              :data="serialNumberList"
              tooltip-effect="dark"
              style="width: 90%"
              @current-change="handleSelectionChange"
            >
              <el-table-column label width="45">
                <template slot-scope="scope">
                  <el-radio :label="scope.row.id" v-model="id"
                    ><span></span
                  ></el-radio>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="序列号" show-overflow-tooltip>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col class="left-content" :span="16">
          <el-table
            max-height="800px"
            size="mini"
            ref="tableProcess"
            :data="processList"
            tooltip-effect="dark"
            @expand-change="expandChange"
            style="width: 100%"
          >
            <!--            <el-table-column type="expand">-->
            <!--                <template  v-if="flag" slot-scope="scope">-->
            <!--                  <div class="resumeMaModels-crad">-->
            <!--                    <el-table-->
            <!--                        size="mini"-->
            <!--                        max-height="650px"-->
            <!--                        :data="scope.row.ResumeMaList"-->
            <!--                        tooltip-effect="dark">-->
            <!--                      <el-table-column prop="mamaschine" label="机器编码" align="center"></el-table-column>-->
            <!--                      <el-table-column prop="mabez" label="机器名称" align="center"></el-table-column>-->
            <!--                      <el-table-column-->
            <!--                          label="操作"-->
            <!--                          width="100">-->
            <!--                        <template slot-scope="scope">-->
            <!--                          <el-button @click="handleClick(scope.row)" v-if="scope.row.resumeMeModels" type="text" size="small">查看特征参数</el-button>-->
            <!--                          <el-button @click="handleClick(scope.row)" v-if="scope.row.imageModel" type="text" size="small">查看图片信息</el-button>-->
            <!--                        </template>-->
            <!--                      </el-table-column>-->
            <!--                    </el-table>-->
            <!--                    <el-table  size="mini"-->
            <!--                               v-if="ResumeMa.resumeMeModels"-->
            <!--                               :data="resumeMeModels"-->
            <!--                               max-height="650px"-->
            <!--                               tooltip-effect="dark">-->
            <!--                      <el-table-column prop="k2002" label="特征名" align="center"></el-table-column>-->
            <!--                      <el-table-column prop="k2142" label="单位" align="center"></el-table-column>-->
            <!--                      <el-table-column prop="k2110" label="上限" align="center"></el-table-column>-->
            <!--                      <el-table-column prop="k2111" label="下限" align="center"></el-table-column>-->
            <!--                      <el-table-column prop="k0001" label="结果" align="center"></el-table-column>-->
            <!--                    </el-table>-->
            <!--                  </div>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column
              prop="prname"
              label="工位号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="prvorname"
              label="工位名称"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  @click="handleMachineClick(scope.row)"
                  type="text"
                  size="small"
                  >查看详情</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>

    <!-- 添加或修改order对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      @close="closeDialog"
      append-to-body
    >
      <div
        class="resumeMaModels-crad"
        v-if="isShowImage == false ? true : false"
      >
        <el-table
          size="mini"
          max-height="650px"
          :data="ResumeMaList"
          tooltip-effect="dark"
        >
          <el-table-column
            prop="mabez"
            label="机器名称"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="text"
                size="small"
                >查看特征参数</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-table
          size="mini"
          v-if="ResumeMa.resumeMeModels"
          :data="resumeMeModels"
          max-height="650px"
          tooltip-effect="dark"
        >
          <el-table-column
            prop="k2002"
            label="特征名"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="k2142"
            label="单位"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="k2110"
            label="上限"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="k2111"
            label="下限"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="k0001"
            label="结果"
            align="center"
          ></el-table-column>
          <el-table-column prop="k0017" label="曲线" align="center">
            <template slot-scope="scope">
              <el-button
                @click="queryCure(scope.row)"
                v-if="scope.row.k0017"
                type="text"
                size="small"
                >查看曲线</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="isShowImage">
        <el-row :gutter="20">
          <el-col
            :span="6"
            v-for="item in imageModels"
            :key="item"
            style="margin-bottom: 20px"
          >
            <el-card :body-style="{ padding: '10px' }">
              <!-- <img :src="item.id" class="image" /> -->
              <el-image
                style="width:100%;height:200px;"
                :src="item.path"
                fit="cover"
                lazy
                :preview-src-list="[item.path]"
              ></el-image>
              <div style="padding: 14px">
                <div class="bottom">
                  <span>{{ item.fileName }}</span>
                  <!-- <el-button type="text" class="button">下载图片</el-button> -->
                  <a class="button" target="_blank" :href="item.path"
                    >下载图片</a
                  >
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 查看曲线 -->
    <el-dialog
      :visible.sync="openCurves"
      width="1020px"
      @close="closeCurvesDialog"
      append-to-body
    >
      <div>
        <div id="CurvesChart" style="height: 400px" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { curvesForceStroke32 } from '@/api/monitor'
import {
  getResumeType,
  getResumeProcess,
  getProductionLineByDate,
  getSerialNumberByDateAndProduction,
  // queryResumeOpAndMaBySerialNumber,
  // queryResumeMeModelBySerialNumAndMachineNum,
  queryOP,
  getSerialNumberDate,
  // getStationBySerialNumber,
  getResumeMeModelBySerialNumberPrname,
} from '@/api/resume'
// import ecStat from "echarts-stat";
import DateTime from '@/components/DateTime/index.vue'
import * as echarts from 'echarts'
import ecStat from 'echarts-stat'

export default {
  components: { DateTime },
  data() {
    return {
      // 弹出层标题
      title: '机器信息',
      // 是否显示弹出层
      open: false,
      //是否显示曲线弹出层
      openCurves: false,
      //曲线数据
      pointData: [],
      //X轴数据
      Xtime: [],
      //Y轴数据
      Ydata: [],
      //曲线图名称
      CurvesTitle: '曲线表',
      //y轴单位
      Yunit: '',
      isShowImage: false,
      //图片列表
      imageModels: [],
      flag: true,
      id: undefined,
      radio3: undefined,
      loading: false,
      serialNumber: undefined,
      form: {
        dateTime: [],
        k1002: undefined,
      },
      serialNumberList: [],
      // ResumeMa: undefined,
      ResumeMa: {
        resumeMeModels: [
          {
            k2002: undefined,
          },
        ],
      },
      resumeMeModels: [],
      ResumeMaList: [],
      image: undefined,
      productionLineList: [],
      types: {
        1: '总装履历表',
        2: '部装履历表',
        3: '线装履历表',
      },
      type: '',
      k0017List: [],
      list: [],
      value: undefined,
      formInline: undefined,
      processList: [],
      total: 40,
      page: 1,
      page_size: 12,
      baseURL: process.env.VUE_APP_BASE_API,
      searchName: '',
      serialNumName: undefined,
      expands: [],
    }
  },
  created() {
    const end_time = new Date().format('yyyy-MM-dd hh:mm:ss')
    let start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24)
    let start_time = new Date(start).format('yyyy-MM-dd hh:mm:ss')

    this.form.dateTime.push(start_time)
    this.form.dateTime.push(end_time)

    // this.form.dateTime.push("2021-12-01 00:00:00");
    // this.form.dateTime.push("2021-12-31 00:00:00");
  },
  mounted() {
    this.getTypes()
    this.queryProductionLineByDate()
  },
  methods: {
    //查询特征参数
    async handleClick(row) {
      // let reqData =  {'K0014':this.serialNumName,'K0010':row.mamaschine}
      // let reqData =  {'K0014':'0S4013515000100BN08ABND02786','K0010': '1105019'}
      // await queryResumeMeModelBySerialNumAndMachineNum(reqData).then(res=>{
      //   this.ResumeMeList = res.data
      // })
      this.ResumeMa = row
      this.resumeMeModels = row.resumeMeModels
      this.k0017List = []
      this.resumeMeModels.forEach((item) => {
        this.k0017List.push(item.k0017)
      })
    },

    //关闭弹窗时的回调
    closeDialog() {
      this.ResumeMeList = []
      this.ResumeMaList = []
      this.pointData = []
      this.imageModels = []
      this.isShowImage = false
      this.Ydata = []
      this.Xtime = []
      this.resumeMeModels = []
    },

    //关闭曲线弹窗回调
    closeCurvesDialog() {
      console.warn('this.pointData:          ' + this.pointData)
      this.Ydata = []
      this.Xtime = []
      this.pointData = []
      console.warn('this.pointData:=============' + this.pointData)
    },

    //根据K0017查询曲线
    async queryCure() {
      const { status, data } = await curvesForceStroke32({
        k0014s: [this.serialNumber],
        k0010: this.ResumeMa.mamaschine,
      })
      if (status == 200) {
        this.openCurves = true
        setTimeout(() => {
          this.drawCurvesHistoryChart1(data)
        }, 100)
      }
    },

    drawCurvesHistoryChart1(res) {
      let series = []
      let colors = []
      let y_min_arr = []
      let y_max_arr = []
      let x_min_arr = []
      let x_max_arr = []
      res.map((item) => {
        const x = item.x
        const y = item.y
        colors.push(item.color)
        let data = x.map((vo, idx) => {
          return [vo, y[idx]]
        })

        y_min_arr.push(ecStat.statistics.min(y))
        y_max_arr.push(ecStat.statistics.max(y))

        x_min_arr.push(ecStat.statistics.min(x))
        x_max_arr.push(ecStat.statistics.max(x))

        series.push({
          name: item.k0014,
          data: data,
          type: 'line',
          smooth: true,
          symbol: 'none',
        })
      })

      let y_min = ecStat.statistics.min(y_min_arr)
      let y_max = ecStat.statistics.max(y_max_arr)
      let x_min = ecStat.statistics.min(x_min_arr)
      let x_max = ecStat.statistics.max(x_max_arr)

      this.$echarts.dispose(document.getElementById('CurvesChart'))
      let chart = this.$echarts.init(document.getElementById('CurvesChart'))
      let option = {
        title: {
          left: 'center',
          text: '力矩位移曲线',
        },
        color: colors,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none',
            },
            dataView: { readOnly: false },
            saveAsImage: {},
            myChange: {
              show: true,
              title: '交换坐标轴',
              icon:
                'path://M560.697 472.022a23 23 0 0 1 13.27 4.214L820.026 650.05c10.375 7.33 12.844 21.681 5.515 32.056a23 23 0 0 1-5.1 5.215L574.383 869.495c-10.21 7.559-24.613 5.41-32.171-4.799a23 23 0 0 1-4.515-13.686V733.816h-201.16c-143.36 0.815-221.206-70.034-233.537-212.546 12.457 13.043 66.902 90 233.537 90 111.09 0 178.144-1.277 201.16-3.828v-112.42c0-12.703 10.297-23 23-23zM406.788 119.304a23 23 0 0 1 4.515 13.686v117.194h201.16c143.36-0.815 221.206 70.034 233.537 212.546-12.457-13.043-66.902-90-233.537-90-111.09 0-178.144 1.277-201.16 3.828v112.42c0 12.703-10.297 23-23 23a23 23 0 0 1-13.27-4.214L128.974 333.95c-10.375-7.33-12.844-21.681-5.515-32.056a23 23 0 0 1 5.1-5.215l246.058-182.173c10.21-7.559 24.613-5.41 32.171 4.799z',
              onclick: function() {
                // let option = params.option;
                let option = chart.getOption()

                let xAxis = JSON.parse(JSON.stringify(option.xAxis))
                let yAxis = JSON.parse(JSON.stringify(option.yAxis))
                option.xAxis = yAxis
                option.yAxis = xAxis

                option.series.map((vo, idx) => {
                  option.series[idx].data = vo.data.map((item) => {
                    return [item[1], item[0]]
                  })
                })

                // return params;
                chart.setOption(option)
              },
            },
          },
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          left: '10%',
          top: 30,
          bottom: 20,
        },
        grid: {
          left: '40%',
          width: '50%',
          // height:"70%",
        },
        xAxis: {
          max: Math.ceil(x_max + 1),
          min: Math.ceil(x_min - 1),
          type: 'value',
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          name: res[0].xunit,
          nameLocation: 'center',
          nameGap: 30,
        },
        yAxis: {
          max: Math.ceil(y_max + 1),
          min: Math.ceil(y_min - 1),
          type: 'value',
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          name: res[0].yunit,
          nameLocation: 'middle',
          nameGap: 30,
        },
        series: series,
      }
      chart.setOption(option)
    },
    //获取图片
    async handleImageClick(row) {
      this.image = row.imageModel
    },

    //根据序列号和工位名称查询机器信息和特征参数以及图片信息
    async handleMachineClick(row) {
      let reqData = { K0014: this.serialNumber, prname: row.prname }
      if (this.serialNumber != undefined) {
        await getResumeMeModelBySerialNumberPrname(reqData).then((res) => {
          this.ResumeMaList = res.data

          this.ResumeMaList.forEach((item) => {
            if (item.imageModel) {
              this.imageModels.push(item.imageModel)
            }
          })

          if (this.imageModels.length > 0) {
            this.isShowImage = true
          }
          this.open = true
        })
      } else {
        this.$message({
          showClose: true,
          message: '请输入或选择序列号！',
          type: 'warning',
        })
      }
    },
    // 展开事件----动态获取内嵌表数据
    async expandChange(row, expandedRows) {
      // console.warn(expandedRows)
      console.warn(row)
      //console.error(expandedRows.length)
      if (expandedRows.length >= 1) {
        this.ResumeMaList = []
        if (row.prname) {
          let reqData = { K0014: this.serialNumber, prname: row.prname }
          console.warn('222222')

          await getResumeMeModelBySerialNumberPrname(reqData).then((res) => {
            row.ResumeMaList = res.data
            setTimeout(() => {
              this.flag = true
            }, 1000)

            // this.$set(row.ResumeMaList,row.ResumeMaList,res.data)

            // this.ResumeMaList.push(row);
            this.$forceUpdate()
          })
          // this.$refs.tableProcess.toggleRowExpansion(expandedRows[0]);
        } else {
          this.ResumeMaList = []
        }

        // 该处是用于判断是展开还是收起行，只有展开的时候做请求，避免多次请求！
        // 展开的时候expandedRows有值，收起的时候为空.
        // if (expandedRows.length > 0) {
        //   rule
        //       .itemSelectByRuleID({
        //         examruleid: row.id
        //       })
        //       .then(res => {
        //         // 遍历当前页面表
        //         this.tableData.forEach((temp, index) => {
        //           // 找到当前点击的行，把动态获取到的数据赋值进去
        //           if (temp.id === row.id) {
        //             this.tableData[index].ruleItemData = res.content;
        //           }
        //         });
        //       });
        // };
      }
    },

    //单选查询工位和机器信息
    async handleSelectionChange(row) {
      this.serialNumName = row.name
      this.serialNumber = row.name
      // await   queryResumeOpAndMaBySerialNumber({'K0014':row.name}).then(res=>{
      //      setTimeout(()=>{
      //        this.processList =res.data
      //      },100)
      //    });
      this.handleAllOP()
    },
    //根据序列号查询工位信息
    async queryStationBynumber() {
      // let K0014 = this.serialNumber ;
      // await getStationBySerialNumber({K0014: this.serialNumber}).then(res=>{
      //   this.processList =res.data;
      // })
      this.handleAllOP()
    },
    //查询所有工位信息
    async handleAllOP() {
      await queryOP().then((res) => {
        this.processList = res.data
      })
    },
    /*更改产线查询序列号*/
    async changeProductLine(row) {
      let reqData = {
        K1002: row,
        beginTime: this.form.dateTime[0],
        endTime: this.form.dateTime[1],
      }
      await getSerialNumberByDateAndProduction(reqData).then((res) => {
        let serialNumberList = []
        if (res.data && res.data.length > 0) {
          res.data.forEach((item, index) => {
            let data = { name: item, id: index }
            serialNumberList.push(data)
          })
        }
        this.serialNumberList = serialNumberList
        this.processList = []
        this.ResumeMeList = []
      })
    },
    /*默认根据时间查询产线以及序列号*/
    async queryProductionLineByDate() {
      let reqData = {
        beginTime: this.form.dateTime[0],
        endTime: this.form.dateTime[1],
      }
      await getProductionLineByDate(reqData).then((res) => {
        this.productionLineList = res.data
      })

      await getSerialNumberDate(reqData).then((res) => {
        let serialNumberList = []
        if (res.data && res.data.length > 0) {
          res.data.forEach((item, index) => {
            let data = { name: item, id: index }
            serialNumberList.push(data)
          })
        }
        this.serialNumberList = serialNumberList
      })
    },

    tableRowClassName({ row }) {
      if (row.type === this.type) {
        return 'select-row'
      }
      return ''
    },
    changeType(row) {
      if (row.type !== this.type) {
        this.type = row.type
        this.getProcess()
      }
    },
    async getTypes() {
      const { data } = await getResumeType()
      this.list = data
      if (this.list[0] && this.list[0].type) {
        this.type = this.list[0].type
        this.getProcess()
      }
      this.loading = false
    },
    async getProcess() {
      // this.loading = true;
      let request_data = {
        type: this.type,
        startTime: this.form.dateTime[0],
        endTime: this.form.dateTime[1],
      }
      const { data } = await getResumeProcess(request_data)
      this.process_list = data

      this.loading = false
    },
    changeDateTime(e) {
      this.form.dateTime = e
      // this.getProcess();
      this.queryProductionLineByDate()
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .has-gutter {
  .el-checkbox {
    display: none;
  }
}
.page-home {
  width: 100% !important;
  height: calc(100vh - 71px);
  color: rgba(16, 16, 16, 100);
  font-family: SourceHanSansSC-regular;
  margin: 0;
  padding: 20px;
  //   margin: auto 0 60px 0;
  .images {
    height: 100%;
    display: flex;
    flex-direction: column;
    .el-row {
      flex: 1;
      overflow: hidden;
    }
  }
  .left-content {
    max-height: 100%;
    overflow-y: scroll;
    .el-card {
      width: 80%;
      /*height: auto;*/
      background: #ffffff;
      color: #000000;
      .process {
        font-weight: bold;
        margin-right: 20px;
      }
      .time {
        float: right;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.page-home {
  .el-date-editor--datetimerange.el-input,
  .el-date-editor--datetimerange.el-input__inner {
    width: 260px !important;
  }
  .el-range-editor--medium .el-range-separator {
    line-height: 32px !important;
  }
  .el-date-editor {
    border: 0 !important;
    padding: 0 !important;
    .el-input__icon {
      display: none !important;
    }
  }
  .el-table--enable-row-hover .el-table__body tr:hover > td {
    background: #3c9ed5;
    color: #fff;
  }
  .select-row {
    background: #3c9ed5;
    color: #fff;
  }
  .el-range-input,
  .el-range-separator {
    color: rgba(39, 97, 219, 100) !important;
    font-size: 12px !important;
  }
}
.title-flex {
  display: flex;
  flex-direction: column;
}
/deep/ .el-radio {
  display: block;
  margin: 15px auto;
  width: 80%;
}

.el-radio-group:first-child {
  /*display: block;*/
  margin: 15px 5px;
  /*width: 80%;*/
}
.resume-checkbox {
  .el-radio-group {
    margin-top: -10px;
  }
  h3 {
    margin-left: 6%;
  }
}

.station-msg-card {
  span {
    font-size: 15px;
    margin-bottom: 50px !important;
  }
  .station-msg-card-grid {
    height: 37px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    grid-column-gap: 20px;
    /*grid-row-gap: 30px;*/
  }
}
.resumeMaModels-crad {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: 1fr;
  grid-column-gap: 20px;
  grid-row-gap: 20px;
}
/*.resume-mamodels-detail{*/
/*  display: flex;*/
/*  justify-content: space-around;*/
/*  span{*/
/*    font-size: 15px;*/
/*  }*/
/*}*/
</style>
